package com.wmd.core.util;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.io.FileChannelRandomAccessSource;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.RandomAccessFileOrArray;
import com.itextpdf.text.pdf.codec.TiffImage;
import sun.awt.image.ImageDecoder;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.Locale;

/**
 * @projectName:DocumentLibrary
 * @packageName:com.wmd.core.util
 * @Description:TODO
 * @Author:luyincheng
 * @CreateDate: 2023/12/510:47
 */
public class PDFUtils {
    public static boolean isTiffFile(String filename) throws IOException {
        Path path=Paths.get(filename);
        String fileExtension= Files.probeContentType(path);
        return "image/tiff".equals(fileExtension);
    }

    public static void TiffToPdf(String tiffFile,String pdfFile) throws IOException, DocumentException {
        if(StringUtil.isEmpty(tiffFile)||StringUtil.isEmpty(pdfFile)){
            return;
        }
        if(!tiffFile.endsWith(".tif")&&!tiffFile.endsWith(".tiff")){
            return;
        }
        if(!pdfFile.endsWith(".pdf")){
            return;
        }
        RandomAccessFile aFile = new RandomAccessFile(tiffFile, "r");
        FileChannel inChannel = aFile.getChannel();
        FileChannelRandomAccessSource fcra =  new FileChannelRandomAccessSource(inChannel);
        Document document = new Document();
        PdfWriter.getInstance(document,  new FileOutputStream(pdfFile));
        document.open();
        RandomAccessFileOrArray rafa = new RandomAccessFileOrArray(fcra);
        int pages = TiffImage.getNumberOfPages(rafa);
        Image image;
        for (int i = 1; i <= pages; i++) {
            image = TiffImage.getTiffImage(rafa, i);
            Rectangle pageSize = new Rectangle(image.getWidth(), image.getHeight());
            document.setPageSize(pageSize);
            document.newPage();
            document.add(image);
        }
        document.close();
        aFile.close();
    }

}
